<?php
/**
 * 前台用户实例
 *
 * PHP Version 5
 *
 * @package    Shop
 * @subpackage Models
 * @author     Weber Liu <weber.liu@gmail.com>
 * @author     Scott Ye <yelin@ec3s.com>
 * @copyright  2010 Xingchangxinda Inc.
 * @version    SVN:$Id: backenduser.php 5128 2011-03-10 09:48:57Z weberliu $
 */

namespace Project\Apps\Ecga\Library;

use \Framework\System\Abstractions\Passport;
use \Project\Apps\Ecga\Library\EcgaPassport;
use \Framework\System\Helper\HttpRequest;
use \Framework\Application\HttpApplication;


/**
 * 前台用户实例
 *
 * @package    Shop
 * @subpackage Models
 * @author     Weber Liu <weber.liu@gmail.com>
 * @author     Scott Ye <yelin@ec3s.com>
 * @copyright  2010 Xingchangxinda Inc.
 * @version    Release: v0.1
 */
class EcgaPassport extends Passport
{

    /**
     * 构造
     *
     * @return void
     */
    public function __construct()
    {
        $this->session = HttpApplication::getInstance()->createSession();
        $this->userModel = $this->getUserModel();
        $this->user = null;
        $this->_checkRemember();
        if ($this->session->item($this->getSessionKey()) > 0) {
            $this->user = $this->getLoggedUser();
        }
    }

    /**
     * 设置记住我
     *
     * @return void
     */
    public function setRemember()
    {
        if ($this->user) {
            setcookie('remember', $this->_encryptRemember($this->user), time() + 3600 * 24 * 30);
        }
    }
    /**
     * 验证记住我
     *
     * @return void
     */
    private function _checkRemember()
    {
        $remember = httpRequest::getInstance()->cookie('remember', 'string');
        if ($remember == '') {
            return;
        }
        list($userId, $userEmail, $verify) = explode('-', $remember);
        if ($userId = '' || $userEmail == '' || $verify == '') {
            $this->outRemember();
            return;
        }
        $user = $this->getUser($userEmail);
        if ($user == '' || $remember != $this->_encryptRemember($user)) {
            $this->outRemember();
            return;
        }
        //设置当前登陆用户
        $this->session->item(
            $this->getSessionKey(), $user->id
        );
    }

    /**
     * 取消记住我
     *
     * @return void
     */
    public function outRemember()
    {
        //使remember过期
        setcookie('remember', '', time() - 1);
    }

    /**
     * 返回一个记住我需要的字符串
     *
     * @param array $user 用户信息
     *
     * @return string
     */
    private function _encryptRemember($user)
    {
        $result = sprintf('%s-%s-%s', $user->id, $user->userEmail, md5($user->userEmail, $user->password));
        return $result;
    }

    /**
     * 根据用户帐号取用户
     *
     * @param string $account 会员帐号
     *
     * @return Entity
     */
    protected function getUser($account)
    {
        $user = $this->userModel->getUser($account);

        return $user === false ? null : $user;
    }

    /**
     * 取用户数据模型
     *
     * @return Model
     */
    protected function getUserModel()
    {
        return model('Users');
    }

    /**
     * 加密
     *
     * @param string $password 密码
     * @param string $salt     扰码
     *
     * @return string 加密后的字符串
     */
    protected function encryptPassword($password, $salt)
    {
        return md5($password . $salt);
    }

     /**
     * 是否有权限
     *
     * @param string $controller 控制器
     * @param string $action     操作
     *
     * @return bool
     * @author Farmer.Li <lixu_01@126.com>
     */
    public function hasPrivilege($controller, $action)
    {
    	if (1 == $this->user->id) {
    		return true;
    	}
    	$start = strrpos($controller, '/') ? strrpos($controller, '/') + 1 : 0;
    	$finalController = strtolower(substr($controller, $start));
    	
    	static $authControllers = array();
    	if ($authControllers == array()) {
    		$privs = model('UserProjectPrivs')->getByUserIdToArray($this->user->id);
    		foreach ($privs as $value) {
    			$authControllers = array_merge($authControllers, $value['privs']);
    		}
    		$authControllers = array_unique($authControllers);
    		$authControllers = array_map('strtolower', $authControllers);
    	}
    	if (in_array($finalController, $authControllers)) {
    		return true;
    	}
        return false;
    }
    
    /**
     * 验证项目权限
     * 
     * @param string $projectId 项目Id
     * @param string $action    操作
     * 
     * @return boolean
     * @author FarmerLi <lixu_01@126.com>
     * @TODO 未实现
     */
    public function hasProjectPriviage($projectId, $action)
    {
    	if (1 == $this->user->id) {
    		return true;
    	}
    	static $privs = null;
    	if (null === $privs) {
    		$privs = model('UserProjectPrivs')->getByUserIdToArray($this->user->id);
    	}
    	if (!$privs) {
    		return false;
    	}
    	if (isset($privs[$projectId]) && in_array($action, $privs[$projectId]['privs'])) {
    		return true;
    	}
    	return false;
    }
}